package com.hzdesk.media.matvector.koreabatch.client.my_paperless.logic.persenter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.hzdesk.media.matvector.koreabatch.client.my_paperless.R;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.bean.LoginInfoBean;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.config.RBConfig;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.logic.contract.IPersonalInformationContract;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.logic.modle.PersonalInformationMolde;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.utils.BitmapUtils;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.utils.FormatUtils;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.utils.JsonUitl;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONObject;

import cn.qqtheme.framework.picker.DatePicker;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/8/15.
 * 杭州席媒科技有限公司  Developers  刘传华  10
 * 佛祖镇楼 bug辟易
 */

public class PersonalInformationPersemter implements IPersonalInformationContract.IPersonalInformationPersemter {
    private IPersonalInformationContract.IPersonalInformationView mIPersonalInformationView;
    private String TAG = PersonalInformationPersemter.class.getSimpleName();
    private IPersonalInformationContract.IPersonalInformationMolde mPersonalInformationMolde ;
    private Handler handler = new Handler();
    public PersonalInformationPersemter(IPersonalInformationContract.IPersonalInformationView mIPersonalInformationView) {
        this.mIPersonalInformationView = mIPersonalInformationView;
        mPersonalInformationMolde= new PersonalInformationMolde();
    }


    @Override
    public void OnclickedPersonImage() {
        mIPersonalInformationView.showPersonImage();
    }

    @Override
    public void OnclickedNiName() {
        mIPersonalInformationView.toNiNamePager();
    }

    @Override
    public void OnclickedPhoneNumber() {

    }

    @Override
    public void OnclickedGender(Context context) {
        View view = View.inflate(context, R.layout.gander_select_layout, null);
        RelativeLayout rl_male = view.findViewById(R.id.gander_select_layout_rl_male);
        RelativeLayout rl_female = view.findViewById(R.id.gander_select_layout_rl_female);
        RelativeLayout rl_cancel = view.findViewById(R.id.gander_select_layout_rl_cancel);
        final PopupWindow popup = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        popup.setAnimationStyle(R.style.ActionSheetDialogAnimation);
        popup.setOutsideTouchable(true);
        popup.setOutsideTouchable(true);
        popup.setTouchable(true);
        popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popup.setFocusable(true);
        popup.setTouchable(true);
        popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popup.showAtLocation(view, Gravity.CENTER,0,0);

        rl_male.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mIPersonalInformationView.setGender("男");
                popup.dismiss();
            }
        });
        rl_female.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mIPersonalInformationView.setGender("女");
                popup.dismiss();
            }
        });
        rl_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup.dismiss();
            }
        });
    }

    @Override
    public void OnclickedDateBirth() {
        mIPersonalInformationView.showDateBirth();
    }

    @Override
    public void OnclickedProfessional() {

    }

    @Override
    public void initTitle() {
        mIPersonalInformationView.showTtile();
    }

    @Override
    public void submitDate(Context context) {
        Log.e(TAG, "onClick: 获取头像url" );
        // todo 获取头像url
        String url = mIPersonalInformationView.getStringUrl();

        if(url != null && !TextUtils.isEmpty(url)){
            Bitmap bitmap = BitmapUtils.imgToBitmap(url);
            if(bitmap != null){
               String base64 =  BitmapUtils.Bitmap2StrByBase64(bitmap);
               if(base64 != null && !TextUtils.isEmpty(base64)){
                   String niName = mIPersonalInformationView.getNiName();

                   if(!TextUtils.isEmpty(niName)){
                      String number =  mIPersonalInformationView.getPhoneNumber();
                      String gender =    mIPersonalInformationView.getGender();
                       // todo 保存niName
                      if(!TextUtils.isEmpty(gender)){
                          int male = 0;
                          if(gender.equals("男")){
                              male= 0;
                          }else if(gender.equals("女")){
                              male= 1;
                          }
                          String formatType = FormatUtils.getImageFormat(url);
                          submitPersonalInformation(base64,niName,number,male,formatType,context,url);
                      }else{
                          mIPersonalInformationView.showToastMessage("请选择性别");
                      }
                   }else{
                       mIPersonalInformationView.showToastMessage("请输入名称");
                   }
               }else{
                   Log.e(TAG, "submitDate: base64 "+base64 );
               }
            }else{
                Log.e(TAG, "submitDate: bitmap "+bitmap );
            }
        }else{
            mIPersonalInformationView.showToastMessage("请选择头像再提交");
        }
    }

    @Override
    public void loadPersonalInfo(final Context context) {
        OkHttpUtils
                .post()
                .url(RBConfig.HOST_IP+RBConfig.LOAD_PERSON_INFO)
                .addHeader("sessionId",mPersonalInformationMolde.getToken(context))
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetWorkResponse = JsonUitl.NetWorkResponse(response);
                        if(NetWorkResponse != null){
                            JSONObject object = JsonUitl.NetworkResponseDateDeal(NetWorkResponse);
                            if(object != null){
                                int codo = JsonUitl.getParsinCode(object);
                                if(codo == 100){
                                    LoginInfoBean loginInfoBean = (LoginInfoBean) JsonUitl.formDate(object, LoginInfoBean.class);
                                    if(loginInfoBean != null){
                                        // todo 存储token 就是 message
                                        String Message = object.getString("message");
                                        mPersonalInformationMolde.savePersonalInfo(context,loginInfoBean);


                                    }
                                }
                            }
                        }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                mIPersonalInformationView.showPresonInfo();
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                mIPersonalInformationView.showPresonInfo();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     * @param  base64 字符串
     * @param niName 名称
     * @param number 账号
     * @param male 性别
     * @param formatType 头像图片类型
     * */
    private void submitPersonalInformation(String base64, final String niName, String number, final int male, String formatType, final Context context, final String url) {
        OkHttpUtils
                .post()
                .url(RBConfig.HOST_IP+RBConfig.MODIFY_INFO)
                .addHeader("sessionId",mPersonalInformationMolde.getToken(context))
                .addParams("id", mPersonalInformationMolde.getId(context))
                .addParams("imageUrl", base64)
                .addParams("imageType", formatType)
                .addParams("realName", niName)
                .addParams("sex", male+"")
                .addParams("mobile", "")
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetWorkResponse = JsonUitl.NetWorkResponse(response);
                        if(NetWorkResponse != null){
                            JSONObject object = JsonUitl.NetworkResponseDateDeal(NetWorkResponse);
                            if(object != null){
                                int codo = JsonUitl.getParsinCode(object);
                                final String Message = object.getString("message");
                                if(codo == 100){
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            handler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    mIPersonalInformationView.showToastMessage("保存成功！");
                                                }
                                            });
                                            // todo 保存url
                                            mPersonalInformationMolde.saveImageUrl(context,url);
                                            // todo 保存niName
                                            mPersonalInformationMolde.saveNiName(context,niName);
                                            // todo 保存性别
                                            mPersonalInformationMolde.saveGender(context,male);
                                            // 退出当前页面
                                            mIPersonalInformationView.finshPager();
                                        }
                                    });
                                }else{
                                    // todo 切换到主线程
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            mIPersonalInformationView.showToastMessage("保存失败！");
                                        }
                                    });
                                }
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                mIPersonalInformationView.showToastMessage("保存失败！");
                            }
                        });
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }


}
